package com.cyh.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 *  异步读1
 * */
public class AsyncFileChannelDemo01 {


    public static void main(String[] args) throws Exception {
       //1 创建AsynchronousFileChannel
        Path path = Paths.get("D:\\cyh\\work_java\\TestNioOrIo\\src\\com\\cyh\\5.txt");
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);

        //2 创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //3 调用channel的read方法得到Future
        Future<Integer> future = fileChannel.read(buffer, 0);

        //4 判断是否完成isDone, 返回true
        while (!future.isDone());

        //5 读取数据到buffer
        buffer.flip();
        /*while (buffer.remaining() > 0) {
            System.out.println(buffer.get());
        }*/

        byte[] data = new byte[buffer.limit()];
        buffer.get(data);
        System.out.println(new String(data));

        buffer.clear();

    }
}
